﻿using Newtonsoft.Json;
using SelfService.Model;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using SelfService.Model.ViewModels;
using SelfService.XinXing.Models;
using TT;

namespace SelfService.XinXing
{
    /// <summary>
    /// HIS用户信息接口
    /// </summary>
    public class User : IHisUser
    {
        private readonly AutoWebService.AutoWebServiceSoapClient _hisClient;
        private readonly AppWebService.AutoWebServiceSoapClient _appClient;

        public User(AutoWebService.AutoWebServiceSoapClient hisClient, AppWebService.AutoWebServiceSoapClient appClient)
        {
            _hisClient = hisClient;
            _appClient = appClient;
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="patient"></param>
        /// <param name="client"></param>
        /// <param name="operator"></param>
        /// <returns></returns>
        public async Task<ResultDetail<IPatient>> GetUserInfo(IPatient patient, SysClient client, SysOperator @operator)
        {
            var request = new HisGetPatientInfoRequest();
            request.Method = "EQ8002";
            if (!patient.CardNo.IsNullOrWhiteSpace())
            {
                request.CardNo = patient.CardNo;
            }else if (!patient.Uid.IsNullOrWhiteSpace())
            {
                request.Uid = patient.Uid;
            }
            else
            {
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = "请提供身份证号码或者身份证UID查询"
                };
            }
            string response = string.Empty;
            try
            {
                response = await _hisClient.ProcessAsync(request.ToXml());
                if (response.XmlTryParseToObject(out HisGetPatientInfoResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        patient.CardNo = result.Item.CardNo;
                        patient.Name = result.Item.PatientName;
                        if(!result.Item.IdCardNo.IsNullOrWhiteSpace()) patient.IdCardNo = result.Item.IdCardNo;
                        if (!result.Item.Uid.IsNullOrWhiteSpace()) patient.Uid = result.Item.Uid;
                        if (!result.Item.Address.IsNullOrWhiteSpace()) patient.Address = result.Item.Address;
                        if (!result.Item.IdCardNo.IsNullOrWhiteSpace()) patient.Balance = result.Item.Balance;
                        if (!result.Item.PatientId.IsNullOrWhiteSpace()) patient.HisCode = result.Item.PatientId;
                        if (!result.Item.Phone.IsNullOrWhiteSpace()) patient.Phone = result.Item.Phone;
                        if (result.Item.Sex == "1") patient.Sex = SexEnum.男;
                        if (result.Item.Sex == "2") patient.Sex = SexEnum.女;
                        if (!patient.IdCardNo.IsNullOrWhiteSpace())
                            patient.Age = Common.GetAgeByIdCardNo(patient.IdCardNo);
                        return new ResultDetail<IPatient>
                        {
                            Data = patient,
                            Request = request.ToXml(),
                            Response = response
                        };
                    }
                    return new ResultDetail<IPatient>()
                    {
                        Code = 1,
                        Message = result.ErrorMsg,
                        Request = request.ToXml(),
                        Response = response
                    };
                }
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = "查询失败, 返回数据解析异常.",
                    Request = request.ToXml(),
                    Response = response
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = $"查询异常:{JsonConvert.SerializeObject(e)}",
                    Request = request.ToXml(),
                    Response = response
                };
            }
        }

        /// <summary>
        /// 通过身份证号码或者身份证ID获取用户卡号
        /// </summary>
        /// <param name="patient"></param>
        /// <param name="client"></param>
        /// <param name="operator"></param>
        /// <returns></returns>
        public async Task<ResultDetail<IPatient>> GetUser(IPatient patient, SysClient client, SysOperator @operator)
        {
            var request = new HisGetPatientCardNoRequest();
            request.Method = "EQ8008";
            if (!patient.IdCardNo.IsNullOrWhiteSpace())
            {
                request.Type = HisGetPatientInfoRequestType.身份证号;
                request.Data = patient.IdCardNo;
            }
            else if (!patient.Uid.IsNullOrWhiteSpace())
            {
                request.Type = HisGetPatientInfoRequestType.身份证id;
                request.Data = patient.Uid;
            }
            else
            {
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = "请提供身份证号码或者身份证UID查询"
                };
            }
            string response = string.Empty;
            try
            {
                response = await _hisClient.ProcessAsync(request.ToXml());
                if (response.XmlTryParseToObject(out HisGetPatientInfoResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        patient.CardNo = result.Item.CardNo;
                        patient.Name = result.Item.PatientName;
                        return await this.GetUserInfo(patient, client, @operator);
                    }
                    return new ResultDetail<IPatient>()
                    {
                        Code = 1,
                        Message = result.ErrorMsg,
                        Request = request.ToXml(),
                        Response = response
                    };
                }
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = "查询失败, 返回数据解析异常.",
                    Request = request.ToXml(),
                    Response = response
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<IPatient>()
                {
                    Code = 1,
                    Message = $"查询异常:{JsonConvert.SerializeObject(e)}",
                    Request = request.ToXml(),
                    Response = response
                };
            }
        }

        public Task<ResultDetail<IPatient>> GetUser(SysPatientSearcher search)
        {
            throw new NotImplementedException();
        }


        public Task<ResultDetail<IPatient>> Reg(IPatient patient, SysClient client, SysOperator @operator)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 通过掌上医院二维码获取用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="client"></param>
        /// <param name="operator"></param>
        /// <returns></returns>
        public async Task<ResultDetail<IPatient>> GetUserByECode(string code, SysClient client, SysOperator @operator)
        {
            var request = new HisECodeRequest { ECode = code };
            var response = await _appClient.GetValueAsync(request.ToXml());
            try
            {
                if (response.XmlTryParseToObject(out ECodeResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        return await this.GetUserInfo(new SysPatient(){CardNo = result.Ec.Code}, client, @operator);
                    }
                    return new ResultDetail<IPatient>
                    {
                        Code = 1,
                        Message = result.ErrorMsg,
                        Request = request.ToXml(),
                        Response = response
                    };
                }
                return new ResultDetail<IPatient>
                {
                    Code = 1,
                    Message = $"查询失败, 返回数据解析异常",
                    Request = request.ToXml(),
                    Response = response
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<IPatient>
                {
                    Code = 1,
                    Message = $"查询异常:{JsonConvert.SerializeObject(e)}",
                    Request = request.ToXml(),
                    Response = response
                };
            }
        }
    }
}